<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="border-card">
      <el-tab-pane label="数据库表结构" name="tables">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="refreshTables"
            >刷新</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleLocalBackup"
              v-hasPermi="['system:database:backup']"
            >本地备份</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleRemoteBackup"
              v-hasPermi="['system:database:backup']"
            >远程备份</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="tableLoading" :data="tableList" height="calc(100vh - 280px)">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column label="表名" prop="tableName" show-overflow-tooltip />
          <el-table-column label="类型" prop="tableType" width="100" align="center" />
          <el-table-column label="备注" prop="remarks" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="viewColumns(scope.row)"
              >结构</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-search"
                @click="viewData(scope.row)"
              >数据</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <el-tab-pane label="SQL查询" name="query">
        <el-form :model="queryForm" ref="queryForm">
          <el-form-item>
            <el-input
              type="textarea"
              :rows="6"
              placeholder="请输入SQL查询语句（仅支持SELECT和SHOW语句）"
              v-model="queryForm.sql"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="executeQuery">执行查询</el-button>
            <el-button @click="resetQuery">清空</el-button>
          </el-form-item>
        </el-form>
        
        <div v-if="queryResult.success">
          <el-alert
            title="查询成功"
            type="success"
            :closable="false"
            show-icon
          ></el-alert>
          <div class="mt10">
            <el-table
              v-loading="queryLoading"
              :data="queryResult.rows"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                v-for="column in queryResult.columnNames"
                :key="column"
                :prop="column"
                :label="column"
                show-overflow-tooltip
              ></el-table-column>
            </el-table>
            <div class="mt10">
              <span>共 {{ queryResult.total }} 条记录</span>
            </div>
          </div>
        </div>
        
        <el-alert
          v-if="queryResult.success === false && queryResult.message"
          :title="queryResult.message"
          type="error"
          :closable="false"
          show-icon
        ></el-alert>
      </el-tab-pane>

      <el-tab-pane label="备份设置" name="backupSettings">
        <el-form ref="backupSettingsForm" :model="backupSettings" :rules="backupSettingsRules" label-width="120px">
          <el-form-item label="定时备份" prop="scheduleBackup">
            <el-radio-group v-model="backupSettings.scheduleBackup">
              <el-radio label="0">不启用</el-radio>
              <el-radio label="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <div v-if="backupSettings.scheduleBackup === '1'">
            <el-form-item label="备份周期" prop="backupCycle">
              <el-radio-group v-model="backupSettings.backupCycle">
                <el-radio label="1">每天</el-radio>
                <el-radio label="2">每周（周一）</el-radio>
                <el-radio label="3">每月（1号）</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="备份时间" prop="backupTime">
              <el-time-picker
                v-model="backupTimeValue"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择时间"
                style="width: 120px;"
                @change="handleTimeChange"
              ></el-time-picker>
              <span class="tips">* 备份将在指定时间自动执行</span>
            </el-form-item>
            
            <el-form-item label="备份方式" prop="backupMethod">
              <el-radio-group v-model="backupSettings.backupMethod">
                <el-radio label="local">本地备份</el-radio>
                <el-radio label="remote">远程备份</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <div v-if="backupSettings.backupMethod === 'remote'">
              <el-form-item label="备份服务器" prop="backupServerId">
                <el-select v-model="backupSettings.backupServerId" placeholder="请选择备份服务器" style="width: 240px;">
                  <el-option
                    v-for="server in serverOptions"
                    :key="server.serverId"
                    :label="server.serverName"
                    :value="server.serverId"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="备份路径" prop="backupPath">
                <el-input v-model="backupSettings.backupPath" placeholder="请输入备份路径" style="width: 400px;">
                  <el-button slot="append" icon="el-icon-folder-opened" @click="showScheduledBackupPathBrowser"></el-button>
                </el-input>
              </el-form-item>
            </div>
            
            <el-form-item label="上次备份时间">
              <span>{{ backupSettings.lastBackupTime ? parseTime(backupSettings.lastBackupTime) : '暂无备份记录' }}</span>
            </el-form-item>
          </div>
          
          <el-form-item>
            <el-button type="primary" @click="saveBackupSettings">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 表结构对话框 -->
    <el-dialog :title="'表结构: ' + currentTable.tableName" :visible.sync="columnDialog" width="800px" append-to-body>
      <el-table :data="columnList" height="450px">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="字段名" prop="columnName" width="150" />
        <el-table-column label="数据类型" prop="dataType" width="100" />
        <el-table-column label="长度" prop="columnSize" width="80" align="center" />
        <el-table-column label="允许为空" width="80" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.nullable" type="success">是</el-tag>
            <el-tag v-else type="danger">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="主键" width="80" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isPrimaryKey" type="warning">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" />
      </el-table>
    </el-dialog>
    
    <!-- 远程备份对话框 -->
    <el-dialog title="远程备份" :visible.sync="remoteBackupDialog" width="600px" append-to-body>
      <el-form ref="remoteBackupForm" :model="remoteBackupForm" :rules="remoteBackupRules" label-width="100px">
        <el-form-item label="目标服务器" prop="targetServerId">
          <el-select 
            v-model="remoteBackupForm.targetServerId" 
            placeholder="请选择目标服务器" 
            style="width: 100%"
            @change="handleServerChange">
            <el-option
              v-for="server in serverOptions"
              :key="server.serverId"
              :label="server.serverName"
              :value="server.serverId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备份路径" prop="backupPath">
          <div class="path-input">
            <el-input 
              v-model="remoteBackupForm.backupPath" 
              placeholder="请选择或输入备份路径"
              :disabled="!remoteBackupForm.targetServerId">
              <el-button slot="append" icon="el-icon-folder-opened" @click="showFileBrowser" :disabled="!remoteBackupForm.targetServerId"></el-button>
            </el-input>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRemoteBackup">确 定</el-button>
        <el-button @click="remoteBackupDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件浏览对话框 -->
    <el-dialog title="选择目录" :visible.sync="fileBrowserDialog" width="600px" append-to-body>
      <div class="file-browser">
        <div class="current-path">
          <span>当前路径: {{ currentPath || '/' }}</span>
        </div>
        <el-table :data="fileList" style="width: 100%" max-height="400">
          <el-table-column label="" width="40">
            <template slot-scope="scope">
              <i class="el-icon-folder" v-if="scope.row.isDirectory"></i>
              <i class="el-icon-document" v-else></i>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称">
            <template slot-scope="scope">
              <el-link 
                type="primary" 
                :underline="false" 
                v-if="scope.row.isDirectory"
                @click="navigateToDirectory(scope.row.path)">
                {{ scope.row.name }}
              </el-link>
              <span v-else>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="permissions" label="权限" width="100"></el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="selectCurrentDirectory">选择当前目录</el-button>
        <el-button @click="fileBrowserDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDatabaseTables, getTableColumns, executeQuery, backupDatabase, remoteBackupDatabase, getDatabase, updateDatabaseBackupSettings } from '@/api/datasync/database';
import { listServerOptions, listServerFiles } from '@/api/datasync/server';
import { parseTime } from '@/utils/ruoyi';

export default {
  name: "DatabaseDetail",
  data() {
    return {
      // 数据库ID
      dbId: null,
      // 激活标签
      activeTab: "tables",
      // 表加载中
      tableLoading: false,
      // 表结构列表
      tableList: [],
      // 查询表单
      queryForm: {
        sql: ""
      },
      // 查询结果
      queryResult: {},
      // 查询中
      queryLoading: false,
      // 表结构对话框
      columnDialog: false,
      // 当前选中表
      currentTable: {},
      // 字段列表
      columnList: [],
      // 远程备份对话框
      remoteBackupDialog: false,
      // 远程备份表单
      remoteBackupForm: {
        targetServerId: null,
        backupPath: ''
      },
      // 远程备份表单校验
      remoteBackupRules: {
        targetServerId: [
          { required: true, message: "请选择目标服务器", trigger: "blur" }
        ],
        backupPath: [
          { required: true, message: "请输入备份路径", trigger: "blur" }
        ]
      },
      // 服务器选项
      serverOptions: [],
      // 文件浏览对话框
      fileBrowserDialog: false,
      // 当前路径
      currentPath: '/',
      // 文件列表
      fileList: [],
      // 备份设置
      backupSettings: {
        scheduleBackup: '0',
        backupCycle: '1',
        backupTime: '',
        backupMethod: 'local',
        backupServerId: null,
        backupPath: '',
        lastBackupTime: null
      },
      // 备份设置校验
      backupSettingsRules: {
        scheduleBackup: [
          { required: true, message: "请选择是否启用定时备份", trigger: "blur" }
        ],
        backupCycle: [
          { required: true, message: "请选择备份周期", trigger: "blur" }
        ],
        backupTime: [
          { required: true, message: "请选择备份时间", trigger: "blur" }
        ],
        backupMethod: [
          { required: true, message: "请选择备份方式", trigger: "blur" }
        ],
        backupServerId: [
          { required: true, message: "请选择备份服务器", trigger: "blur" }
        ],
        backupPath: [
          { required: true, message: "请输入备份路径", trigger: "blur" }
        ]
      },
      // 备份时间值
      backupTimeValue: ''
    };
  },
  created() {
    this.dbId = parseInt(this.$route.query.dbId);
    if (!this.dbId) {
      this.$message.error('数据库ID不能为空');
      return;
    }
    this.refreshTables();
    this.getServerOptions();
    this.getBackupSettings();
  },
  methods: {
    /** 刷新表结构列表 */
    refreshTables() {
      if (!this.dbId) {
        return;
      }
      this.tableLoading = true;
      getDatabaseTables(this.dbId).then(response => {
        this.tableList = response.data;
        this.tableLoading = false;
      }).catch(() => {
        this.tableLoading = false;
      });
    },
    
    /** 获取服务器选项 */
    getServerOptions() {
      listServerOptions().then(response => {
        this.serverOptions = response.data;
      });
    },
    
    /** 获取备份设置 */
    getBackupSettings() {
      getDatabase(this.dbId).then(response => {
        if (response.code === 200) {
          const data = response.data;
          // 设置备份数据
          this.backupSettings.scheduleBackup = data.scheduleBackup || '0';
          this.backupSettings.backupCycle = data.backupCycle || '1';
          this.backupSettings.backupTime = data.backupTime || '';
          this.backupTimeValue = data.backupTime || '';
          this.backupSettings.backupServerId = data.backupServerId;
          this.backupSettings.backupPath = data.backupPath || '';
          this.backupSettings.lastBackupTime = data.lastBackupTime;
          
          // 根据是否有备份服务器判断备份方式
          this.backupSettings.backupMethod = data.backupServerId ? 'remote' : 'local';
        }
      });
    },
    
    /** 本地备份数据库 */
    handleLocalBackup() {
      this.$modal.confirm('确认要对当前数据库进行本地备份吗？').then(() => {
        this.$modal.loading("正在备份中，请稍候...");
        backupDatabase(this.dbId).then(response => {
          this.$modal.closeLoading();
          if (response.code === 200) {
            // 提取备份文件路径
            let filePath = '';
            if (response.msg && response.msg.includes('：')) {
              filePath = response.msg.split('：')[1];
              // 显示成功信息和文件路径
              this.$modal.msgSuccess("备份成功，文件保存在：" + filePath);
            } else {
              this.$modal.msgSuccess(response.msg);
            }
          } else {
            this.$modal.msgError(response.msg);
          }
        }).catch(() => {
          this.$modal.closeLoading();
        });
      });
    },
    
    /** 打开远程备份对话框 */
    handleRemoteBackup() {
      this.remoteBackupForm.targetServerId = null;
      this.remoteBackupForm.backupPath = '';
      this.remoteBackupDialog = true;
    },
    
    /** 处理服务器选择变化 */
    handleServerChange(serverId) {
      if (serverId) {
        // 获取服务器默认备份路径
        const server = this.serverOptions.find(s => s.serverId === serverId);
        if (server && server.backupPath) {
          this.remoteBackupForm.backupPath = server.backupPath;
        } else {
          this.remoteBackupForm.backupPath = '/backup/database';
        }
      } else {
        this.remoteBackupForm.backupPath = '';
      }
    },
    
    /** 显示文件浏览器 */
    showFileBrowser() {
      if (!this.remoteBackupForm.targetServerId) {
        this.$modal.msgError("请先选择目标服务器");
        return;
      }
      
      this.currentPath = '/';
      this.fileList = [];
      this.fileBrowserDialog = true;
      this.loadDirectoryContents(this.currentPath);
    },
    
    /** 加载目录内容 */
    loadDirectoryContents(dirPath) {
      // 根据当前场景选择正确的服务器ID
      let serverId = null;
      if (this.remoteBackupForm.targetServerId) {
        // 远程备份对话框场景
        serverId = this.remoteBackupForm.targetServerId;
      } else if (this.backupSettings.backupServerId) {
        // 定时备份设置场景
        serverId = this.backupSettings.backupServerId;
      }

      if (!serverId) {
        this.$modal.msgError("请先选择服务器");
        return;
      }

      this.$modal.loading("正在加载目录内容...");
      listServerFiles(serverId, dirPath).then(response => {
        this.$modal.closeLoading();
        if (response.code === 200) {
          this.fileList = response.data.filter(item => item.isDirectory); // 只显示目录
          this.currentPath = dirPath;
        } else {
          this.$modal.msgError("加载目录内容失败: " + response.msg);
        }
      }).catch(() => {
        this.$modal.closeLoading();
      });
    },
    
    /** 导航到指定目录 */
    navigateToDirectory(dirPath) {
      this.loadDirectoryContents(dirPath);
    },
    
    /** 选择当前目录 */
    selectCurrentDirectory() {
      // 根据当前场景设置正确的路径
      if (this.remoteBackupForm.targetServerId) {
        // 远程备份对话框场景
        this.remoteBackupForm.backupPath = this.currentPath;
      } else if (this.backupSettings.backupServerId) {
        // 定时备份设置场景
        this.$set(this.backupSettings, 'backupPath', this.currentPath);
      }
      this.fileBrowserDialog = false;

      // 显示成功提示
      this.$modal.msgSuccess('路径选择成功：' + this.currentPath);
    },
    
    /** 提交远程备份 */
    submitRemoteBackup() {
      this.$refs.remoteBackupForm.validate(valid => {
        if (valid) {
          this.$modal.confirm('确认要对当前数据库进行远程备份吗？').then(() => {
            this.$modal.loading("正在备份中，请稍候...");
            remoteBackupDatabase(
              this.dbId, 
              this.remoteBackupForm.targetServerId,
              this.remoteBackupForm.backupPath
            ).then(response => {
              this.$modal.closeLoading();
              if (response.code === 200) {
                this.remoteBackupDialog = false;
                // 提取备份文件路径
                let filePath = '';
                if (response.msg && response.msg.includes('：')) {
                  filePath = response.msg.split('：')[1];
                  // 显示成功信息和文件路径
                  this.$modal.msgSuccess("远程备份成功，文件保存在：" + filePath);
                } else {
                  this.$modal.msgSuccess(response.msg);
                }
              } else {
                this.$modal.msgError(response.msg);
              }
            }).catch(() => {
              this.$modal.closeLoading();
            });
          });
        }
      });
    },
    
    /** 查看表结构 */
    viewColumns(row) {
      this.currentTable = row;
      this.columnDialog = true;
      this.columnList = [];
      
      getTableColumns(this.dbId, row.tableName).then(response => {
        this.columnList = response.data;
      });
    },
    
    /** 查看表数据 */
    viewData(row) {
      // 设置查询SQL
      this.queryForm.sql = `SELECT * FROM ${row.tableName} LIMIT 100`;
      this.activeTab = "query";
      this.executeQuery();
    },
    
    /** 执行SQL查询 */
    executeQuery() {
      if (!this.queryForm.sql) {
        this.$modal.msgError("请输入SQL查询语句");
        return;
      }
      
      this.queryLoading = true;
      executeQuery(this.dbId, this.queryForm.sql).then(response => {
        this.queryResult = response.data;
        this.queryLoading = false;
      }).catch(() => {
        this.queryLoading = false;
      });
    },
    
    /** 清空查询 */
    resetQuery() {
      this.queryForm.sql = "";
      this.queryResult = {};
    },
    
    /** 显示备份路径浏览器 */
    showScheduledBackupPathBrowser() {
      if (!this.backupSettings.backupServerId) {
        this.$modal.msgError("请先选择备份服务器");
        return;
      }
      
      this.currentPath = '/';
      this.fileList = [];
      this.fileBrowserDialog = true;
      this.loadDirectoryContents(this.currentPath);
    },
    
    /** 处理备份时间变化 */
    handleTimeChange(time) {
      this.backupSettings.backupTime = time;
    },
    
    /** 保存备份设置 */
    saveBackupSettings() {
      this.$refs.backupSettingsForm.validate(valid => {
        if (valid) {
          const data = {
            dbId: this.dbId,
            scheduleBackup: this.backupSettings.scheduleBackup,
            backupCycle: this.backupSettings.backupCycle,
            backupTime: this.backupSettings.backupTime
          };
          
          // 如果选择远程备份，添加相关参数
          if (this.backupSettings.backupMethod === 'remote') {
            data.backupServerId = this.backupSettings.backupServerId;
            data.backupPath = this.backupSettings.backupPath;
          } else {
            // 本地备份时设置为null
            data.backupServerId = null;
            data.backupPath = null;
          }
          
          updateDatabaseBackupSettings(data).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess('备份设置保存成功');
              this.getBackupSettings(); // 刷新设置
            } else {
              this.$modal.msgError(response.msg);
            }
          });
        }
      });
    },
    
    /** 解析时间 */
    parseTime(timestamp) {
      return parseTime(timestamp);
    }
  }
};
</script>

<style scoped>
.mt10 {
  margin-top: 10px;
}
.mb8 {
  margin-bottom: 8px;
}
.path-input {
  display: flex;
  align-items: center;
}
.current-path {
  margin-bottom: 10px;
  font-weight: bold;
}
.file-browser {
  min-height: 300px;
}
</style> 